<script setup>
import {onMounted, ref, watch, computed} from "vue";
import {useFunctionsStore} from "stores/functions";
import {useUiStore} from "stores/ui";
import {isConnected, status} from "src/utils/deviceWs";
import RouteComponents from "components/common/RouteComponents.vue";
import {storeToRefs} from "pinia";
import {Dialog, Notify, useQuasar} from "quasar";
import {useAPIStore} from "stores/api";
import {api} from "boot/axios";
import {useRouter} from "vue-router";
import {useI18n} from "vue-i18n";

const t = useI18n().t;
const appList = [
  {
    title: t("PostureIndex.路径管理"),
    icon: "route",
    link: "RouteManage",
  },
  {
    title: t("PostureIndex.库位管理"),
    icon: "account_tree",
    link: "StorageManage",
  },
  {
    title: t("PostureIndex.绑定关系"),
    icon: "device_hub",
    link: "BoundManage",
  },
];

const $q = useQuasar();
const ui = useUiStore();
const router = useRouter();
const visible = ref(false); //  弹窗显示
const tab = ref("select"); //  tab页切换
const isEdit = ref(false); //  是否编辑场景
const {scene} = storeToRefs(useFunctionsStore()); //  当前场景
const textScene = ref(""); // 所有input的值
const selectScene = ref({}); // select的值
const sceneOptions = ref([]); //  场景选项列表
// const scenarioId = computed(() => status.value.scenarioId); // 后端场景id
const isConnect = computed(() => isConnected.value); // 是否连接机器人
const isClose = ref(false); // 是否可直接关闭场景
const loading = ref(false); // 加载load

onMounted(() => {
  // 未连接直接退出
  watch(
      () => isConnect.value,
      (connected) => {
        if (!connected) {
          dialogHint(t("PostureIndex.未连接机器人"));
          isClose.value = true;
        }
      }
  );

  // 获取场景列表
  getSceneList();
  // 延时判断
  // setTimeout(() => {
  //   setScene();
  // }, 500);
});
// 监听后端场景发生改变
watch(() => status.value.scenarioId, () => {
  console.log('后端场景发生改变', status.value.scenarioId)
  setScene();
});
//  监听弹窗显示
watch(visible, (val) => {
  if (val) {
    tab.value = "select";
    isEdit.value = false;
    selectScene.value = scene.value;
  }
});

// 监听标签页
watch(tab, (val) => {
  switch (val) {
    case "select":
      selectScene.value = scene.value;
      isEdit.value = false;
      break;
    case "del":
      selectScene.value = "";
      break;
    default:
      textScene.value = "";
      break;
  }
});

// 场景发生改变设置场景加条件判断
function setScene() {
  // 机器人未选择场景
  if (!status.value.scenarioId) {
    dialogHint(t("PostureIndex.机器人未选择场景"));
    isClose.value = true;
    return;
  }
  // 机器人场景和选择的场景不符
  if (scene.value.id !== status.value.scenarioId) {
    dialogHint(t("PostureIndex.机器人场景和选择的场景不符"));
    isClose.value = true;
  }
  // 筛选出场景列表中是否包含机器人上场景
  selectScene.value = sceneOptions.value.filter(
      (item) => item.id === status.value.scenarioId
  )[0];
  // 没包含显示弹窗重新选择场景
  if (!selectScene.value) {
    dialogHint(t("PostureIndex.机器人上场景未从列表中查到"));
    isClose.value = true;
    return;
  }
  // 缓存赋值场景
  scene.value = selectScene.value;
  // 可直接关闭弹窗
  isClose.value = false;
}

// 场景弹窗提醒
function dialogHint(message) {
  $q.dialog({
    dark: ui.isDark,
    title: message,
    ok: t("know"),
    cancel: false,
    persistent: true,
  }).onOk(() => {
    if (message === t("PostureIndex.未连接机器人")) {
      router.push("/main");
    } else {
      visible.value = true;
    }
  });
}

// 获取场景列表
function getSceneList() {
  api
      .get(useAPIStore().postureUrl + "scenario/scenarios")
      .then((rs) => {
        if (rs.data.code === 200) {
          sceneOptions.value = rs.data.data;
        } else {
          $q.notify({
            message: t("PostureIndex.场景列表获取失败"),
            type: "negative",
          });
        }
      })
      .catch(() => {
        $q.notify({
          message: t("PostureIndex.场景列表获取异常"),
          type: "negative",
        });
      });
}

// 新建场景
function createScene() {
  if (!textScene.value)
    return Notify.create({
      type: "negative",
      message: t("PostureIndex.请输入场景名"),
    });
  api
      .post(useAPIStore().postureUrl + "scenario/scenario", {
        name: textScene.value,
      })
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({
            message: t("PostureIndex.场景创建成功"),
            type: "positive",
          });
          getSceneList();
          tab.value = "select";
        } else {
          $q.notify({
            message: t("PostureIndex.场景创建失败"),
            type: "negative",
          });
        }
      })
      .catch(() => {
        $q.notify({message: t("RequestError"), type: "negative"});
      });
}

// 编辑场景
function editScene() {
  if (!textScene.value)
    return Notify.create({
      type: "negative",
      message: t("PostureIndex.请填写新场景名称"),
    });
  selectScene.value.name = textScene.value;
  api
      .put(useAPIStore().postureUrl + "scenario/scenario", selectScene.value)
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({
            message: t("PostureIndex.场景修改成功"),
            type: "positive",
          });
          goScene();
          visible.value = false;
        } else {
          $q.notify({
            message: t("PostureIndex.场景修改失败"),
            type: "negative",
          });
        }
      })
      .catch(() => {
        $q.notify({message: t("RequestError"), type: "negative"});
      });
}

// 删除场景
function delScene() {
  if (!selectScene.value)
    return Notify.create({
      type: "negative",
      message: t("PostureIndex.请选择场景"),
    });
  Dialog.create({
    class: "text-space",
    dark: ui.isDark,
    title: t("PostureIndex.是否确认删除场景") + "-" + selectScene.value.name,
    message: t("PostureIndex.删除操作将清空该场景下的所有姿态路径及库位"),
    prompt: {
      model: "",
      placeholder: t("PostureIndex.输入delete即可删除"),
      isValid: (val) => val === "delete",
      type: "text", // optional
    },
    cancel: true,
    persistent: true,
  }).onOk(() => {
    api
        .delete(
            useAPIStore().postureUrl + "scenario/scenario/" + selectScene.value.id
        )
        .then((rs) => {
          if (rs.data.code === 200) {
            $q.notify({
              message: t("PostureIndex.场景删除成功"),
              type: "positive",
            });
            if (selectScene.value.id === scene.value.id) {
              scene.value = "";
            }
            visible.value = false;
          } else {
            $q.notify({
              message: t("PostureIndex.场景删除失败"),
              type: "negative",
            });
          }
        })
        .catch(() => {
          $q.notify({message: t("RequestError"), type: "negative"});
        });
  });
}

// 选择确认场景
function goScene() {
  if (!selectScene.value) {
    Notify.create({type: "negative", message: t("PostureIndex.请选择场景")});
    return;
  }
  loading.value = true;
  api
      .post(useAPIStore().amrUrl + "ros/call", [selectScene.value.id], {
        params: {service: "/scenario_server"},
      })
      .then((res) => {
        if (res.data.values.result === "SUCCESS") {
          $q.notify({
            message: t("PostureIndex.场景切换成功"),
            type: "positive",
          });
          scene.value = selectScene.value;
          loading.value = false;
          visible.value = false;
        } else {
          $q.notify({
            message: t("PostureIndex.场景切换失败"),
            type: "negative",
          });
          loading.value = false;
          retry();
        }
      })
      .catch(() => {
        $q.notify({message: t("RequestError"), type: "negative"});
        loading.value = false;
        retry();
      });
}

// 重试提示切换场景
function retry() {
  $q.dialog({
    dark: ui.isDark,
    title: t("tips"),
    message: t("PostureIndex.请确认机器人程序是否正常运行"),
    ok: t("PostureIndex.重试"),
    cancel: t("PostureIndex.退出"),
    persistent: true,
  })
      .onOk(() => {
        goScene();
      })
      .onCancel(() => {
        router.push("/main");
      });
}
</script>

<template>
  <div class="column">
    <route-components :appList="appList" class="full-height"/>
    <div
        :class="ui.isDark ? 'text-white' : 'text-black'"
        class="absolute-bottom text-weight-bold text-space text-h6 text-center q-mb-lg"
    >
      {{
        $t("PostureIndex.当前场景")
      }}<span
        class="cursor-pointer text-over text-underline text-primary"
        @click="visible = true"
    >{{ scene.name || $t("PostureIndex.请选择") }}</span
    >
    </div>
    <q-dialog v-model="visible" :persistent="isClose">
      <q-card style="min-width: 350px">
        <q-tabs
            v-model="tab"
            dense
            :class="ui.btnClass"
            align="justify"
            narrow-indicator
        >
          <q-tab no-caps name="select" :label="$t('PostureIndex.选择场景')"/>
          <q-tab no-caps name="create" :label="$t('PostureIndex.新建场景')"/>
          <q-tab no-caps name="del" :label="$t('PostureIndex.删除场景')"/>
        </q-tabs>

        <q-separator/>

        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="select">
            <q-card-section>
              <q-input
                  outlined
                  autofocus
                  v-model="textScene"
                  :label="$t('PostureIndex.所选场景') + selectScene.name"
                  stack-label
                  :placeholder="$t('PostureIndex.请输入新场景名称')"
                  v-if="isEdit"
              />
              <q-select
                  v-else
                  outlined
                  v-model="selectScene"
                  :options="sceneOptions"
                  :label="$t('PostureIndex.请选择场景')"
                  option-label="name"
              />
            </q-card-section>
            <q-card-section align="right" v-if="isEdit">
              <q-btn
                  no-caps
                  class="q-mx-md"
                  :class="ui.btnClass"
                  :label="$t('PostureIndex.返回选择')"
                  @click="isEdit = false"
              />
              <q-btn
                  no-caps
                  :class="ui.btnClass"
                  :label="$t('PostureIndex.确认编辑')"
                  @click="editScene"
              />
            </q-card-section>
            <q-card-section align="right" v-else>
              <q-btn
                  no-caps
                  class="q-mr-md"
                  :class="ui.btnClass"
                  :label="$t('PostureIndex.退出')"
                  @click="router.push('/main')"
              />
              <q-btn
                  no-caps
                  class="q-mr-md"
                  :class="ui.btnClass"
                  :label="$t('PostureIndex.编辑场景')"
                  @click="isEdit = true"
                  v-show="selectScene"
              />
              <q-btn
                  no-caps
                  :class="ui.btnClass"
                  :label="$t('PostureIndex.确认选择')"
                  @click="goScene"
              />
            </q-card-section>
          </q-tab-panel>

          <q-tab-panel name="create">
            <q-card-section>
              <q-input
                  outlined
                  v-model="textScene"
                  :label="$t('PostureIndex.请输入场景名')"
              />
            </q-card-section>
            <q-card-section align="right">
              <q-btn
                  :class="ui.btnClass"
                  :label="$t('PostureIndex.确认新建')"
                  @click="createScene"
              />
            </q-card-section>
          </q-tab-panel>

          <q-tab-panel name="del">
            <q-card-section>
              <q-select
                  outlined
                  v-model="selectScene"
                  :options="sceneOptions"
                  :label="$t('PostureIndex.请选择场景')"
                  option-label="name"
              />
            </q-card-section>
            <q-card-section align="right">
              <q-btn
                  no-caps
                  class="text-space text-bold"
                  color="negative"
                  :label="$t('PostureIndex.确认删除')"
                  @click="delScene"
              />
            </q-card-section>
          </q-tab-panel>
        </q-tab-panels>
      </q-card>
    </q-dialog>
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary"/>
      <span
          class="q-mt-lg text-h5"
          :class="ui.isDark ? 'text-white' : 'text-black'"
      >{{ $t("PostureIndex.场景切换中") }}</span
      >
    </q-inner-loading>
  </div>
</template>
